package com.cxb;

import java.io.File;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.Selection;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cxb.manager.WifiApManager;
import com.cxb.manager.WifiApManager.OnWifiApStateChangedListener;
import com.cxb.utils.SharedPreferencesUtils;
import com.cxb.utils.WifiAPUtil;
import com.cxb.view.SwitchButton;
import com.cxb.view.SwitchButton.OnChangedListener;
import com.cxb.view.TTSToast;
import com.lidroid.xutils.BitmapUtils;

public class WifiAPActivity extends BaseActivity implements
		OnWifiApStateChangedListener {
	private EditText etPassword;
	private TextView et_ssid;
	private CheckBox cbShowPassword;
	private Button ibSave;
	private SwitchButton wiperSwitch;
	private TextView wifi_noaptips;
	SharedPreferencesUtils sp;
	private BitmapUtils bitmapUtils;
	// private SetWifiApThread swat;
	private WifiManager wifiManager;
	private WifiApManager wifiApHandler;

	WifiAPUtil mWifiUtil = new WifiAPUtil();
	private CheckBox.OnCheckedChangeListener checkBox_Listener = new CheckBox.OnCheckedChangeListener() {
		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			if (cbShowPassword.isChecked()) {
				// 文本正常显示
				etPassword
						.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
				Editable etable = etPassword.getText();
				Selection.setSelection(etable, etable.length());
			} else {
				// 文本以密码形式显示
				etPassword.setInputType(InputType.TYPE_CLASS_TEXT
						| InputType.TYPE_TEXT_VARIATION_PASSWORD);
				// 下面两行代码实现: 输入框光标一直在输入文本后面
				Editable etable = etPassword.getText();
				Selection.setSelection(etable, etable.length());
			}

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setting_wifiap);
		sp = new SharedPreferencesUtils(WifiAPActivity.this);
		bitmapUtils = new BitmapUtils(this);
		init();
		initWifiApData();
		wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		wifiApHandler = new WifiApManager(this);
		wifiApHandler.registerReceiver();
		wifiApHandler.registerWifiApStateChangedListener(this);
	}

	@Override
	protected void onDestroy() {
		wifiApHandler.unregisterReceiver();
		super.onDestroy();
	}

	private void init() {
		et_ssid = (TextView) findViewById(R.id.et_ssid);
		et_ssid.setText(sp.getWifiApSSID());
		wifi_noaptips = (TextView) findViewById(R.id.tv_wifi_noaptips);
		etPassword = (EditText) findViewById(R.id.et_password);
		etPassword.setText(sp.getWifiApPassword());
		cbShowPassword = (CheckBox) findViewById(R.id.cb_show_password);
		cbShowPassword.setOnCheckedChangeListener(checkBox_Listener);



		wiperSwitch = (SwitchButton) findViewById(R.id.wiperSwitch);
		wiperSwitch.setOnChangedListener(new OnChangedListener() {

			@Override
			public void OnChanged(View wiperSwitch, boolean checkState) {
				boolean enable = mWifiUtil.getWifiApState(wifiManager) == WifiAPUtil.WIFI_AP_STATE_ENABLED;
				if (checkState != enable)
					wifiApHandler.changeWifiApState(checkState);
				// setViewVisible();
			}
		});
		wiperSwitch
				.setChecked(mWifiUtil.getWifiApState(wifiManager) == WifiAPUtil.WIFI_AP_STATE_ENABLED);
		setViewVisible();
	}

	private void setViewVisible() {
		if (wiperSwitch.isOn()) {
			wifi_noaptips.setVisibility(View.GONE);
			findViewById(R.id.ll_ssid).setVisibility(View.VISIBLE);
			findViewById(R.id.tv_password).setVisibility(View.VISIBLE);
			findViewById(R.id.et_password).setVisibility(View.VISIBLE);
			findViewById(R.id.tv_wifiqrcode).setVisibility(View.VISIBLE);
			findViewById(R.id.iv_wifiqrcode).setVisibility(View.VISIBLE);
			setWifiqrcodeEnable(true);
		} else {
			findViewById(R.id.ll_ssid).setVisibility(View.GONE);
			findViewById(R.id.tv_password).setVisibility(View.GONE);
			findViewById(R.id.et_password).setVisibility(View.GONE);
			findViewById(R.id.tv_wifiqrcode).setVisibility(View.GONE);
			findViewById(R.id.iv_wifiqrcode).setVisibility(View.GONE);
			setWifiqrcodeEnable(false);
			wifi_noaptips.setVisibility(View.VISIBLE);
		}
	}

	private void save() {
		// TODO Auto-generated method stub
		// ssidetPassword能为空，密码可以为空
		if (etPassword.getText().toString() == null
				|| etPassword.getText().toString().length() < 8) {
			TTSToast.show(getApplicationContext(),
					getString(R.string.wifi_ap_password_too_short),
					Toast.LENGTH_SHORT);
			return;
		}
		// sp.setWifiApSSID(etSSID.getText().toString());
		sp.setWifiApPassword(etPassword.getText().toString());
		TTSToast.show(getApplicationContext(),
				getString(R.string.save_success), Toast.LENGTH_SHORT);

	}

	//
	// private void setWifiApTh(boolean state) {
	//
	// swat = new SetWifiApThread(state);
	// Thread thread = new Thread(swat);
	// thread.start();
	// }

	// class SetWifiApThread implements Runnable {
	// boolean wifiapstate;
	//
	// public SetWifiApThread(boolean state) {
	// super();
	// wifiapstate = state;
	// }
	//
	// @Override
	// public void run() {
	//
	// Message msg = mHandler.obtainMessage();
	// int state = mWifiUtil.getWifiApState(wifiManager);
	// if (wifiapstate) {
	// if (state == WifiAPUtil.WIFI_AP_STATE_DISABLED
	// || state == WifiAPUtil.WIFI_AP_STATE_FAILED) {
	// String ssid = sp.getWifiApSSID();
	// String password = sp.getWifiApPassword();
	// mWifiUtil.setWifiAp(wifiManager, sp.getWifiApSSID(),
	// sp.getWifiApPassword(), wifiapstate);
	// mHandler.postDelayed(swat, 200);
	// } else if (state == WifiAPUtil.WIFI_AP_STATE_ENABLING
	// || state == WifiAPUtil.WIFI_AP_STATE_FAILED) {
	// mHandler.postDelayed(swat, 200);
	// } else if (state == WifiAPUtil.WIFI_AP_STATE_ENABLED) {
	// TTSToast.show(WifiAPActivity.this,
	// getString(R.string.ap_opened), 2000);
	// }
	// } else {
	// if (state == WifiAPUtil.WIFI_AP_STATE_DISABLED) {
	// TTSToast.show(WifiAPActivity.this,
	// getString(R.string.ap_closed), 2000);
	//
	// } else if (state == WifiAPUtil.WIFI_AP_STATE_DISABLING
	// || state == WifiAPUtil.WIFI_AP_STATE_FAILED) {
	// mHandler.postDelayed(swat, 200);
	// } else if (state == WifiAPUtil.WIFI_AP_STATE_ENABLED) {
	// mWifiUtil.setWifiAp(wifiManager, sp.getWifiApSSID(),
	// sp.getWifiApPassword(), wifiapstate);
	// mHandler.postDelayed(swat, 200);
	// }
	// }
	// msg.what = state;
	// mHandler.sendMessage(msg);
	// }
	// }

	@Override
	public void onWifiApStateChanged(int state) {

		// if (state == WifiAPUtil.WIFI_AP_STATE_DISABLED) {
		// Toast.makeText(this, getString(R.string.wifiap_close), 0).show();
		// // TTSToast.show(this, getString(R.string.wifiap_close), 0);
		//
		// } else if (state == WifiAPUtil.WIFI_AP_STATE_ENABLED) {
		// Toast.makeText(this, getString(R.string.wifiap_open), 0).show();
		// // TTSToast.show(this, getString(R.string.wifiap_open), 0);
		// }
		wiperSwitch.setChecked(state == WifiAPUtil.WIFI_AP_STATE_ENABLED);
		setViewVisible();
	}

	private String ImageUrl = null;
	private String ssid = null;
	private String ssid_password = null;

	private void initWifiApData() {
		File sqrFile = new File("/system/media/wifiap");
		if (sqrFile.exists()) {
			if (sqrFile.list() != null && sqrFile.list().length > 0) {
				String tempName = sqrFile.list()[0];
				Log.d("pumkid", tempName);
				if (tempName.endsWith(".png") || tempName.endsWith(".jpg")
						|| tempName.endsWith(".jpeg")) {
					ImageUrl = tempName;
				}
			}
		} else
			return;
		if (ImageUrl == null)
			return;
		String[] nameNpassward = ImageUrl.split("_");
		for (int i = 0; nameNpassward != null && i < nameNpassward.length; i++) {
			if (i == 0) {
				ssid = nameNpassward[i];
				sp.setWifiApSSID(ssid);
				// et_ssid.setText(nameNpassward[i]);
			}
			if (i == 1) {
				ssid_password = (String) nameNpassward[i].substring(0,
						nameNpassward[i].indexOf("."));
				sp.setWifiApPassword(ssid_password);
				// et_password.setText(nameNpassward[i].subSequence(0,
				// nameNpassward[i].indexOf(".")));
			}
		}
	}

	private void setWifiqrcodeEnable(boolean enable) {

		ImageView iv_wifiqrcode = (ImageView) findViewById(R.id.iv_wifiqrcode);
		if (!enable) {
			iv_wifiqrcode.setVisibility(View.GONE);
			return;
		}
		initWifiApData();
		iv_wifiqrcode.setVisibility(View.VISIBLE);

		if (ImageUrl == null) {
			return;
		}

		TextView et_ssid = (TextView) findViewById(R.id.et_ssid);
		TextView et_password = (TextView) findViewById(R.id.et_password);

		if (ssid != null)
			et_ssid.setText(ssid);
		if (ssid_password != null)
			et_password.setText(ssid_password);

		bitmapUtils.display(iv_wifiqrcode, "/system/media/wifiap/" + ImageUrl);
	}
}
